package array;

public class BinarySearch {


    /**
     * 二分查询 左闭右闭
     *
     * @param arr    数组
     * @param target 目标值
     * @date: 2025.8.3
     */
    public static int searchMethod(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        //1.找到中间索引
        int mid = (left + right) / 2;
        while (left <= right) {
            //2.目标值 <中间值 右区间区间向左移动
            if (target < arr[mid]) {
                right = mid - 1;
            }
            //3.目标值 >中间值 左区间向右移动
            else if (target > arr[mid]) {
                left = mid + 1;
            }else {
                //4.目标值 == 中间值 找到目标并返回
                return mid;
            }

        }
        //5.都没找到的话返回-1
        return -1;
    }

    public static void main(String[] args) {
        int arr[] = {1,3,4,5,6,7,8,9};
        int target = 5;
        int i = searchMethod(arr, target);
        System.out.println("i = " + i);
    }
}
